<?php
namespace app\servercertificate\logic;
use \app\manage\logic\BaseLogic;
use \think\Db;

/**
 * @author:      李颖
 * @DateTime:    2017-06-16 16:17:51
 * @Description: 证书转让
 */
class TransferLog extends BaseLogic
{
	protected $name = 'transfer_log';
    protected $config = 'db_config_certificate';
    protected $certificateLogic = 'app\servercertificate\logic\Certificate';
    protected $transferLogModel = 'app\servercertificate\model\TransferLog';
    protected $certificateModel = 'app\servercertificate\model\Certificate';
    protected $searchWhere = ['certificate_id'=>'eq','user_id'=>'eq','to_user'=>'eq','status'=>'in'];


    /*证书转让*/
    public function transfer($data): array 
    {
        //添加转让记录
        $data['status'] = 0;
        $data['is_last'] = 1;
        //将其他我转让过的证书的is_last改为0
        $_updateIsLastWhere['certificate_id'] = $data['certificate_id'];
        $_updateIsLastWhere['user_id'] = $data['user_id'];
        $_updateIsLastWhere['status'] = ['neq', 0];
        $_updateIsLastWhere['is_last'] = 1;
        $this->model($this->transferLogModel)->where($_updateIsLastWhere)->update(['is_last'=>0]);

        $addLog = $this->model($this->transferLogModel)->save($data);
        if(!$addLog){
            return auto_failure(null, '添加证书转让记录失败');
        }
        $res = $this->model($this->transferLogModel)->getLastInsID();
        
        /*证书转让时，修改证书转让状态*/
        $_where['id'] = $data['certificate_id'];
        $_where['user_id'] = $data['user_id'];
        $_where['is_transfer'] = 0;
        $_where['status'] = 1;
        $res = $this->model($this->certificateModel)->save(['is_transfer'=>1],$_where);
        if(!$res){
            return auto_failure(null, '修改证书转让状态错误');
        }

        return auto_success($res, '证书已转让中，请等待对方同意');
    }

    /*艺货 - 证书退款 用户将证书直接转让给平台*/
    public function transferDirect($data): array 
    {
        $this->db()->startTrans();
        try{
            //添加转让记录  状态为同意证书转让
            $data['status'] = 1;
            $addLog = $this->model($this->transferLogModel)->save($data);
            if(!$addLog){
                $this->db()->rollback();
                return auto_failure(null, '添加证书转让记录失败');
            }
            //修改证书信息
            $_where['certificate_id'] = $data['certificate_id'];
            $info = $this->model($this->transferLogModel)->field('certificate_info', true)->where($_where)->order('id desc')->find()->toArray();
            $updateCerti = logic($this->certificateLogic)->transferCertificateDirect($info, true);  /*修改证书信息*/
            if($updateCerti['status'] != SUCCESS_STATUS){
                $this->db()->rollback();
                return $updateCerti;
            }
            $this->db()->commit();
        }catch(\Exception $e){
            $this->db()->rollback();
            return auto_failure(null, $e->getMessage());
        } 
        return auto_success($updateCerti, '证书成功退款/退证书');
    }

    /*根据条件获取某证书某转让记录详情*/
    public function dbTransferInfo($data)
    {
    	$_where = $this->searchWhere($data, $this->searchWhere);
    	return $this->db()->where($_where)->find();
    }

    public function transferInfo($data)
    {
        $_where = $this->searchWhere($data, $this->searchWhere);
        return $this->model($this->transferLogModel)->where($_where)->find();
    }

    /*对方同意或拒绝证书的转让*/
    public function replyTransfer($data, bool $isAgree): array 
    {

        $_where['certificate_id'] = $data['certificate_id'];
        $_where['to_user'] = $data['to_user'];
        $_where['status'] = 0;

        $this->db()->startTrans();
       
        try{
            $status = $isAgree ? 1 : 2;
            $msg = $isAgree ? '同意' : '拒绝';

            $transferLog = $this->model($this->transferLogModel)->field('certificate_info', true)->where($_where)->find();
            if(!$transferLog){
                return verify_err(null, '没有找到该转让记录');
            }
            $transferLog && $transferLog->toArray();
            $transferLog['status'] = $status;
            $transferLog['create_time'] = NOW;
            $transferLog['update_time'] = NOW;
            
            $updateRes = $this->model($this->transferLogModel)->save(['status'=>$status],$_where);
            if(!$updateRes){
                return auto_failure(null, '修改转让记录中的状态错误');
            }
            $updateCerti = logic($this->certificateLogic)->transferCertificate($transferLog, $isAgree);  /*修改证书信息*/
            if($updateCerti['status'] != SUCCESS_STATUS){
                return $updateCerti;
            }  
            $this->db()->commit();

        }catch(\Exception $e){

            $this->db()->rollback();
            return auto_failure(null, $e->getMessage());
        }
        return auto_success($updateCerti, '已'.$msg.'证书的转让');

    }

    /*获取我未处理（to_user有值user_id无值）的证书列表 和 我已转让成功（user_id有值to_user无值）的证书列表*/
    public function transferCertiList($data): array 
    {
        if(isset($data['type']) && $data['type']){ $_where['certificate.type'] = $data['type']; } 
        
        if($data['user_id']){  //获取我已转让成功的证书列表
            $_where['transfer_log.is_last'] = 1; //避免重复
            $_where['transfer_log.user_id'] = $data['user_id']; 
            $_where['transfer_log.status'] = 1; 
            $_where['certificate.user_id'] = ['neq', $data['user_id']];
        }
        if($data['to_user']){  //获取我未处理的证书列表
            $_where['transfer_log.to_user'] = $data['to_user'];
            $_where['transfer_log.status'] = 0; 
        }
        
        $res = Db::connect(config('db_config_certificate'))
        ->view('certificate', 'id,name,product_code,earnings,is_transfer,status,create_time,update_time,goods_info')
        ->view('transfer_log', 'certificate_id,status as transfer_log_status', 'certificate.id = transfer_log.certificate_id', 'LEFT')
        ->where($_where)
        ->order('update_time', 'desc')
        ->paginate(null,false,['page'=>$data['page'],'list_rows'=>$data['listRows']])
        ->toArray();
        foreach ($res['data'] as $k => &$v) {
            $v['goods_info'] = json_decode($v['goods_info'], true);
            $v['is_transfer_text'] = $v['is_transfer'] == 1 ? '转让中' : '';
        }
        return auto_return_page($res);
    }

    /*获取某个证书的转让记录 分页*/
    public function getTransferList($data): array 
    {
        $_where['certificate_id'] = $data['certificate_id'];
        $data['keywords'] && $_where['user_info$.name|to_user_info$.name'] = ['like', '%' . $data['keywords'] . '%'];
        $list = $this->model($this->transferLogModel)
                    ->field('certificate_info', true)
                    ->where($_where)
                    ->order('create_time desc')
                    ->paginate(null, false, ['page'=>$data['page'], 'list_rows'=>$data['listRows']])
                    ->toArray();
        return auto_return_page($list, '成功获取该证书的转让记录列表', '获取证书的转让记录列表失败');
    }



}